package com.wiz.weixin.controllor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.wiz.weixin.criteria.WxPayCriteria;
import com.wiz.weixin.manager.TencentManager;
import com.wiz.weixin.service.MemberService;
import com.wiz.weixin.service.PayService;
import com.wiz.weixin.service.StationService;
import com.wiz.weixin.to.HQBaseInfoTO;
import com.wiz.weixin.to.PayOrderTO;
import com.wiz.weixin.util.PastUtil;
import com.wiz.weixin.vo.MemberVO;

/**
 * 会员
 * @author xxy
 */
@Controller
@RequestMapping("/pay")
public class PayControllor {
	private transient final Logger log = LoggerFactory.getLogger(getClass());
	
	private final String HQ_CHARGE="%s充值";

	@Resource
	private PayService payService;
	@Resource
	private StationService stationService;
	@Resource
	private MemberService memberService;
	@Resource
	private TencentManager tencentManager;

	/**准备支付*/
	@RequestMapping(value = "/toCharge" ,method = RequestMethod.GET)
	public String toPay(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "memberId", required = true) String memberId,
			@RequestParam(value = "hqId", required = true) String hqId, 
			HttpSession session, Model model) throws Exception{
		// 将请求、响应的编码均设置为UTF-8（防止中文乱码）
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		String agent = request.getHeader("User-Agent").toLowerCase();
		if (!agent.contains("micromessenger")) {
			model.addAttribute("msg", "请使用微信自带的浏览注册！");
			return "/error";
		}
		String openId = (String) session.getAttribute("openid");
//		String openId = "ovNRGs45WudglvjfjUth3W57tJOU";
		if (StringUtils.isBlank(openId)) {
			String code = request.getParameter("code");
			openId = tencentManager.getOpenId(code);
		}
		if(StringUtils.isBlank(openId)){
			model.addAttribute("msg", "不能得到你的微信编码！");
			return "/error";
		}
		session.setAttribute("openid", openId);
		HQBaseInfoTO hqConfig = stationService.getHqConfigById(hqId);
		if(hqConfig.getChargeStatus() != 1){
			model.addAttribute("msg", "该功能未开放");
			return "/error";
		}
		MemberVO memberVO = memberService.getMemberByOpenId(openId, hqId);
		if(memberVO == null){
			model.addAttribute("msg", "没有找到当前油站对应的会员！");
			return "/error";
		}
		if(memberVO.getStatus() != 1){
			model.addAttribute("msg", "账户已冻结或已注销！");
			return "/error";
		}
		model.addAttribute("member", memberVO);
		log.info("openId="+openId+" will use web pay");
		return "/pay/pay";
	}

	/** 授权 */
	@RequestMapping(value = "/prepay/", method = RequestMethod.POST)
	public String prepay(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "hqId", required = true) String hqId,
			@RequestParam(value = "hqName", required = true) String hqName,
			@RequestParam(value = "stationId", required = true) String stationId,
			@RequestParam(value = "memberId", required = true) String memberId,
			@RequestParam(value = "type", required = true) Integer type,
			@RequestParam(value = "memberFrozenAmount", required = true) Double memberFrozenAmount,
			HttpSession session, Model model) throws Exception {
		// 将请求、响应的编码均设置为UTF-8（防止中文乱码）
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		String openId = (String) session.getAttribute("openid");
		if (StringUtils.isBlank(openId)) {
			model.addAttribute("msg", "不能得到你的微信编码！");
			return "/error";
		}
		PastUtil.setJsSdkInModel(model);
		WxPayCriteria criteria = new WxPayCriteria();
		criteria.setOpenId(openId);
		criteria.setUseType(type);
		if(type == 2){//在线充值
			criteria.setBody(String.format(HQ_CHARGE, hqName));
			criteria.setUseType(2);
		}
		int totalFee = (int)(memberFrozenAmount*100);
		criteria.setTotalFee(totalFee);
		PayOrderTO to = payService.getWxUnifiled(hqId, stationId, criteria);
		model.addAttribute("payTO",to);
		model.addAttribute("hqId",hqId);
		model.addAttribute("stationId",stationId);
		return "/pay/startpay";
	}
	
	/** 授权 */
	@RequestMapping(value = "/succ" ,method = RequestMethod.GET)
	public String paySuccess(HttpServletRequest request, HttpServletResponse response,
			HttpSession session, Model model) throws Exception {
		model.addAttribute("msg", "充值成功，稍后到帐");
		return "/success";
	}
	
	/** 授权 */
	@RequestMapping(value = "/fail" ,method = RequestMethod.GET)
	public String payFail(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "hqId", required = true) String hqId,
			@RequestParam(value = "stationId", required = true) String stationId,
			@RequestParam(value = "payOrderId", required = true) String payOrderId,
			HttpSession session, Model model) throws Exception {
		payService.closeWebOrder(hqId, stationId, payOrderId);
		model.addAttribute("msg", "充值失败");
		return "/error";
	}
}
